var carousels = document.querySelector('.carousel'),
	figure = carousels.querySelector('figure'),   //ul
	nav = carousels.querySelector('nav'),
	lis = figure.children,    //ul li
	n = lis.length,
	gap = carousels.dataset.gap,
	bfc = 'bfc' in carousels.dataset,
	theta = 2 * Math.PI / n,
	now_index = 0;

//动态根据下拉框应尽图片
select_box.addEventListener("change", function() {
	last_index = 0;
	now_index = 0;
	add_img(this.value);
})

function add_img(options) {
	// 动态加图片
	var xhr = new XMLHttpRequest();
	xhr.open("GET", "http://build.bluej.cn/api/index/get_carousel/position_id/" + options, false);
	xhr.send("");

	if(xhr.readyState == 4) {
		if(xhr.status == 200) {
			figure.innerHTML = "";
			getimg();
			//JSON.stringify(obj);  json转string
		}
	}

	function getimg() {
		var data = JSON.parse(xhr.responseText);
		for(var i = 0; i < data.data.length; i++) {
			figure.innerHTML += "<li><img src='http://build.bluej.cn" + data.data[i].ch_img_url + "'/></li>";
			lis = document.querySelectorAll("figure li");
			carousels = document.querySelector('.carousel');
			figure = carousels.querySelector('figure');
			nav = carousels.querySelector('nav');
			lis = figure.children;
			n = lis.length;
			gap = carousels.dataset.gap;
			bfc = 'bfc' in carousels.dataset;
			theta = 2 * Math.PI / n;
		}

	}

}
add_img(1);


// 加载3D
setupCarousel(n, parseFloat(getComputedStyle(lis[0]).width));
window.addEventListener('change', function() {
	setupCarousel(n, parseFloat(getComputedStyle(lis[0]).width));
});

setupNavigation();


//  图片变化
function setupCarousel(n, s) {
	var apothem = s / (2 * Math.tan(Math.PI / n));

	figure.style.transformOrigin = '50% 50% ' + -apothem + 'px';

	for(var i = 0; i < n; i++) {
		lis[i].style.padding = gap + 'px';
	}
	for(i = 1; i < n; i++) {
		lis[i].style.transformOrigin = '50% 50% ' + -apothem + 'px';
		lis[i].style.transform = 'rotateY(' + i * theta + 'rad)';
	}
	
	//是否隐藏被遮挡的图片
	if(bfc)
		for(i = 0; i < n; i++) {
			lis[i].style.backfaceVisibility = 'hidden';
		}
	rotateCarousel(now_index);
}


//  移动
function setupNavigation() {
	nav.addEventListener('click', onClick, true);

	function onClick(e) {
//		e.stopPropagation();

		var t = e.target;
		if(t.tagName.toUpperCase() != 'BUTTON') return;

		if(t.classList.contains('next')) {
			now_index++;
		} else {
			now_index--;
		}

		rotateCarousel(now_index);
	}
}


function rotateCarousel(imageIndex) {
	figure.style.transform = 'rotateY(' + imageIndex * -theta + 'rad)';
}